﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Net;

using System.IO;
using System.Data;
using System.Collections;
using System.Xml;


namespace BattleshipGameClient
{
    public partial class ConnectionForm : Form
    {
        private Connection connection;
        public int status = 0;
        public string username = "";
        public string password = "";

        Dictionary<string, User> userList = new Dictionary<string, User>();

        //0: waiting for other palyers
        //1: in game

        public ConnectionForm(Connection connection)
        {
            this.connection = connection;

            InitializeComponent();

            txtIPLabel.Text = connection.getUri().AbsoluteUri;
            this.dataGridView1.Visible = false;

        }

        public void showForm(Form frm)
        {
            if (InvokeRequired)
                BeginInvoke((Action)delegate {
                    showForm(frm);
                });
            else
                frm.Show();
        }


        private void btnConnect_Click(object sender, EventArgs e)
        {
            Uri remoteUri;
            ConnectionStatus.Text = "Connecting...";
            this.Refresh();
            try
            {
                remoteUri = new Uri(connectTo.Text);
                
            }
            catch
            {
                ConnectionStatus.Text = "Invalid Uri";
                return;
            }


            if (connection.getConnection(remoteUri) == null)
            {
                ConnectionStatus.Text = "Couldn't connect to the uri.";
                return;
            }
            int remoteStatus = connection.queryPlayerStatus();
            if (remoteStatus == 1)
            {
                ConnectionStatus.Text = "This player is ready for a new game.";
                startButton.Visible = true;
                btnConnect.Visible = false;
            }
            else if (remoteStatus == 2)
                ConnectionStatus.Text = "This player is already playing.";

            chatButton.Visible = true;
            btnNewConn.Visible = true;
            connectTo.Enabled = false;
        }

        public String getName()
        {
            return inpDisplayName.Text;
        }

        private void chatButton_Click(object sender, EventArgs e)
        {
            connection.openChat();
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            connection.selfRequestNewGame();
        }

        private void btnNewConn_Click(object sender, EventArgs e)
        {
            ConnectionStatus.Text = "";
            btnNewConn.Visible = false;
            btnConnect.Visible = true;
            startButton.Visible = false;
            chatButton.Visible = false;
            connectTo.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            

            HttpWebRequest req;
            string strGet = "http://localhost:8080/IBattleship.asmx/login?username=" + this.textBox1.Text.Trim() + "&password=" + this.maskedTextBox1.Text;
            strGet = strGet + "";
            req = (HttpWebRequest)WebRequest.Create(strGet);
            HttpWebResponse response;
            response = (HttpWebResponse)req.GetResponse();
            Stream stream = response.GetResponseStream();
            XmlTextReader reader = new XmlTextReader(stream);
            reader.MoveToContent();


            string result = reader.ReadInnerXml();
            reader.Close();

            if (Convert.ToBoolean(result))
            {
                MessageBox.Show("Login success");
                this.label2.Visible = false;
                this.label4.Visible = false;
                this.textBox1.Visible = false;
                this.maskedTextBox1.Visible = false;
                this.button1.Visible = false;

                this.username = textBox1.Text;
                this.password = maskedTextBox1.Text;

                this.getOnline();
                this.showData();
                this.dataGridView1.Visible = true;

            }
            else {
                MessageBox.Show("Login failed");
            }
        }

        public void getOnline() {

            HttpWebRequest req;
            string strGet = "http://localhost:8080/IBattleship.asmx/getOnline?username=" + this.textBox1.Text.Trim() + "&password=" + this.maskedTextBox1.Text+"&ip="+this.connection.getUri().Host+"&port="+this.connection.getUri().Port;
            strGet = strGet + "";
            req = (HttpWebRequest)WebRequest.Create(strGet);
            HttpWebResponse response;
            response = (HttpWebResponse)req.GetResponse();

        }

        public void showData() {
            HttpWebRequest req;
            string strGet = "http://localhost:8080/IBattleship.asmx/getUserList";
            strGet = strGet + "";
            req = (HttpWebRequest)WebRequest.Create(strGet);
            HttpWebResponse response;
            response = (HttpWebResponse)req.GetResponse();
            Stream stream = response.GetResponseStream();
            XmlTextReader reader = new XmlTextReader(stream);
            reader.MoveToContent();
            

           // while(reader.)


            string result = reader.ReadInnerXml();

            string[] users = result.Split(';');

            for (int i = 0; i < users.Length; i++) {
                string[] userinfo = users[i].Split(',');
                MessageBox.Show(userinfo.Length+"");
                User user = new User();
                user.username = userinfo[0];
                user.nickname = userinfo[1];
                user.ip = userinfo[2];
                user.port = userinfo[3];
                user.status = Convert.ToInt32(userinfo[4]);
                user.win = Convert.ToInt32(userinfo[5]);
                user.lose = Convert.ToInt32(userinfo[6]);

                this.userList.Add(userinfo[0], user);

               
            }
            reader.Close();

                System.Windows.Forms.BindingSource bs = new System.Windows.Forms.BindingSource();
                bs.DataSource = userList.Values;
                this.dataGridView1.DataSource = bs;

                
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Uri remoteUri;
            ConnectionStatus.Text = "Connecting...";
            this.Refresh();
            try
            {
                remoteUri = new Uri(connectTo.Text);

            }
            catch
            {
                ConnectionStatus.Text = "Invalid Uri";
                return;
            }


            if (connection.getConnection(remoteUri) == null)
            {
                ConnectionStatus.Text = "Couldn't connect to the uri.";
                return;
            }
            int remoteStatus = connection.queryPlayerStatus();
            if (remoteStatus == 1)
            {
                ConnectionStatus.Text = "This player is ready for a new game.";
                startButton.Visible = true;
                btnConnect.Visible = false;
            }
            else if (remoteStatus == 2)
                ConnectionStatus.Text = "This player is already playing.";

            chatButton.Visible = true;
            btnNewConn.Visible = true;
            connectTo.Enabled = false;
        }

    }
}
